import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import json
import time
import os
import requests
from video_generator import VideoGenerator
from image_generator import ImageGenerator

class VideoTabManager:
    def __init__(self, parent_frame, api_key_entry):
        self.parent_frame = parent_frame
        self.api_key_entry = api_key_entry
        self.video_task_id = None
        self.last_video_result = None
        self.init_image_to_video_tab()
    

    
    def init_image_to_video_tab(self):
        # 图片生成视频区域
        image_to_video_frame = ttk.LabelFrame(self.parent_frame, text="图片生成视频-首帧")
        image_to_video_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 提示词输入
        prompt_frame = ttk.Frame(image_to_video_frame)
        prompt_frame.pack(fill=tk.X, padx=5, pady=5)
        
        ttk.Label(prompt_frame, text="提示词:").pack(anchor=tk.W, padx=5)
        self.image_to_video_prompt_text = tk.Text(prompt_frame, height=6, width=60)
        self.image_to_video_prompt_text.pack(fill=tk.X, padx=5, pady=5)
        
        # 示例提示词
        example_prompt = "女孩抱着狐狸，女孩睁开眼，温柔地看向镜头，狐狸友善地抱着，镜头缓缓拉出，女孩的头发被风吹动  --ratio adaptive  --dur 5"
        self.image_to_video_prompt_text.insert(tk.END, example_prompt)
        
        # 图片上传
        image_upload_frame = ttk.Frame(image_to_video_frame)
        image_upload_frame.pack(fill=tk.X, padx=5, pady=5)
        
        ttk.Label(image_upload_frame, text="选择图片:").pack(anchor=tk.W, padx=5)
        self.image_path_entry = ttk.Entry(image_upload_frame, width=50)
        self.image_path_entry.pack(side=tk.LEFT, padx=5, pady=5)
        
        self.browse_image_btn = ttk.Button(image_upload_frame, text="浏览", command=self.browse_image)
        self.browse_image_btn.pack(side=tk.LEFT, padx=5)
        
        # 操作按钮
        action_frame = ttk.Frame(image_to_video_frame)
        action_frame.pack(fill=tk.X, padx=5, pady=5)
        
        self.generate_image_to_video_btn = ttk.Button(action_frame, text="生成视频", command=self.generate_image_to_video)
        self.generate_image_to_video_btn.pack(side=tk.LEFT, padx=5)
        
        self.check_image_to_video_status_btn = ttk.Button(action_frame, text="检查状态", command=self.check_image_to_video_status, state=tk.DISABLED)
        self.check_image_to_video_status_btn.pack(side=tk.LEFT, padx=5)
        
        # 结果展示区域
        result_frame = ttk.Notebook(image_to_video_frame)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 文本结果标签页
        text_frame = ttk.Frame(result_frame)
        result_frame.add(text_frame, text="文本结果")
        self.image_to_video_result_text = tk.Text(text_frame, height=15)
        self.image_to_video_result_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 视频结果标签页
        self.image_to_video_display_frame = ttk.Frame(result_frame)
        result_frame.add(self.image_to_video_display_frame, text="视频结果")
        self.image_to_video_label = ttk.Label(self.image_to_video_display_frame, text="视频将在此处显示")
        self.image_to_video_label.pack(pady=20)
        self.image_to_video_player = None
        
        # 保存结果按钮
        self.save_image_to_video_result_btn = ttk.Button(action_frame, text="保存结果", command=self.save_image_to_video_result, state=tk.DISABLED)
        self.save_image_to_video_result_btn.pack(side=tk.LEFT, padx=5)
    
    def browse_image(self):
        file_path = filedialog.askopenfilename(
            title="选择图片",
            filetypes=[("Image files", "*.jpg *.jpeg *.png *.bmp")]
        )
        if file_path:
            self.image_path_entry.delete(0, tk.END)
            self.image_path_entry.insert(0, file_path)
    
    def generate_image_to_video(self):
        # 获取输入参数
        api_key = self.api_key_entry.get()
        prompt = self.image_to_video_prompt_text.get("1.0", tk.END).strip()
        image_path = self.image_path_entry.get().strip()
        
        # 检查必要参数
        if not api_key:
            messagebox.showerror("错误", "请先配置API Key")
            return
        
        if not prompt:
            messagebox.showerror("错误", "请输入提示词")
            return
        
        if not image_path:
            messagebox.showerror("错误", "请选择图片")
            return
        
        try:
            # 上传图片以获取URL
            image_generator = ImageGenerator(api_key=api_key)
            image_url = image_generator.upload_image_to_get_url(image_path)
            
            # 导入视频生成器
            video_generator = VideoGenerator(api_key=api_key)
            
            # 发送请求
            self.image_to_video_result_text.delete("1.0", tk.END)
            self.image_to_video_result_text.insert(tk.END, "正在生成视频...\n")
            self.parent_frame.update()
            
            result = video_generator.generate_video_from_image(prompt, image_url)
            
            # 保存任务ID用于后续查询
            self.image_to_video_task_id = result["task_id"]
            
            # 显示结果
            self.image_to_video_result_text.delete("1.0", tk.END)
            self.image_to_video_result_text.insert(tk.END, json.dumps(result, indent=2, ensure_ascii=False))
            
            # 启用检查状态按钮
            self.check_image_to_video_status_btn.config(state=tk.NORMAL)
        
        except Exception as e:
            error_msg = f"请求异常: {str(e)}"
            self.image_to_video_result_text.delete("1.0", tk.END)
            self.image_to_video_result_text.insert(tk.END, error_msg)
    
    def check_image_to_video_status(self):
        # 获取输入参数
        api_key = self.api_key_entry.get()
        
        # 检查必要参数
        if not api_key:
            messagebox.showerror("错误", "请先配置API Key")
            return
        
        if not hasattr(self, 'image_to_video_task_id'):
            messagebox.showerror("错误", "请先生成视频任务")
            return
        
        try:
            # 导入视频生成器
            video_generator = VideoGenerator(api_key=api_key)
            
            # 查询任务状态
            self.image_to_video_result_text.delete("1.0", tk.END)
            self.image_to_video_result_text.insert(tk.END, "正在查询任务状态...\n")
            self.parent_frame.update()
            
            result = video_generator.get_video_generation_status(self.image_to_video_task_id)
            
            # 显示结果
            self.image_to_video_result_text.delete("1.0", tk.END)
            self.image_to_video_result_text.insert(tk.END, json.dumps(result, indent=2, ensure_ascii=False))
            
            # 如果视频已生成完成，启用保存按钮
            if result["status"] == "succeeded":  # 根据用户提供的示例，状态应为 succeeded
                self.save_image_to_video_result_btn.config(state=tk.NORMAL)
                self.last_image_to_video_result = result
                
                # 下载并显示视频
                self.download_and_display_image_to_video(result)
        
        except Exception as e:
            error_msg = f"请求异常: {str(e)}"
            self.image_to_video_result_text.delete("1.0", tk.END)
            self.image_to_video_result_text.insert(tk.END, error_msg)
    
    def save_image_to_video_result(self):
        if not hasattr(self, 'last_image_to_video_result'):
            messagebox.showwarning("警告", "没有可保存的结果")
            return
        
        # 选择保存路径
        file_path = filedialog.asksaveasfilename(
            title="保存结果",
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if file_path:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    json.dump(self.last_image_to_video_result, f, indent=2, ensure_ascii=False)
                messagebox.showinfo("成功", "结果已保存")
            except Exception as e:
                messagebox.showerror("错误", f"保存结果失败: {str(e)}")
    
    def download_and_display_image_to_video(self, result):
        """下载并显示生成的视频"""
        try:
            # 从结果中获取视频URL
            video_url = None
            
            # 检查不同的可能结构
            if "content" in result and result["content"]:
                content = result["content"]
                # 如果content是列表，检查列表中的元素
                if isinstance(content, list) and len(content) > 0:
                    first_item = content[0]
                    if isinstance(first_item, dict) and "video_url" in first_item:
                        video_url = first_item["video_url"]
                # 如果content是字典，直接检查video_url
                elif isinstance(content, dict) and "video_url" in content:
                    video_url = content["video_url"]
            
            # 如果在content中没找到，检查result
            if not video_url and "result" in result and result["result"]:
                res = result["result"]
                if isinstance(res, dict) and "video_url" in res:
                    video_url = res["video_url"]
            
            if video_url:
                # 下载视频
                video_path = self.download_video(video_url)
                
                # 在UI中显示视频
                self.display_image_to_video(video_path)
            else:
                self.image_to_video_label.config(text="未找到视频URL")
        except Exception as e:
            self.image_to_video_label.config(text=f"处理视频时出错: {str(e)}")
    
    def display_image_to_video(self, video_path):
        """在UI中显示视频"""
        # 显示视频路径和播放按钮
        self.image_to_video_label.config(text=f"视频已生成: {video_path}")
        
        # 添加播放视频按钮
        if hasattr(self, 'image_to_video_play_button'):
            self.image_to_video_play_button.destroy()
        self.image_to_video_play_button = tk.Button(self.image_to_video_display_frame, text="播放视频", command=lambda: self.play_video(video_path))
        self.image_to_video_play_button.pack(pady=10)
    

    
    def download_and_display_video(self, result):
        """下载并显示生成的视频"""
        try:
            # 从结果中获取视频URL
            video_url = None
            
            # 检查不同的可能结构
            if "content" in result and result["content"]:
                content = result["content"]
                # 如果content是列表，检查列表中的元素
                if isinstance(content, list) and len(content) > 0:
                    first_item = content[0]
                    if isinstance(first_item, dict) and "video_url" in first_item:
                        video_url = first_item["video_url"]
                # 如果content是字典，直接检查video_url
                elif isinstance(content, dict) and "video_url" in content:
                    video_url = content["video_url"]
            
            # 如果在content中没找到，检查result
            if not video_url and "result" in result and result["result"]:
                res = result["result"]
                if isinstance(res, dict) and "video_url" in res:
                    video_url = res["video_url"]
            
            if video_url:
                # 下载视频
                video_path = self.download_video(video_url)
                
                # 在UI中显示视频
                self.display_video(video_path)
            else:
                self.video_label.config(text="未找到视频URL")
        except Exception as e:
            self.video_label.config(text=f"处理视频时出错: {str(e)}")
    
    def download_video(self, video_url):
        """下载视频文件"""
        # 生成唯一的文件名
        filename = f"generated_video_{int(time.time())}.mp4"
        video_path = os.path.join("generated_videos", filename)
        
        # 下载视频
        response = requests.get(video_url)
        response.raise_for_status()
        
        with open(video_path, "wb") as f:
            f.write(response.content)
        
        return video_path
    
    def display_video(self, video_path):
        """在UI中显示视频"""
        # 显示视频路径和播放按钮
        self.video_label.config(text=f"视频已生成: {video_path}")
        
        # 添加播放视频按钮
        if hasattr(self, 'play_button'):
            self.play_button.destroy()
        self.play_button = tk.Button(self.video_display_frame, text="播放视频", command=lambda: self.play_video(video_path))
        self.play_button.pack(pady=10)
        
    def play_video(self, video_path):
        """使用系统默认播放器播放视频"""
        try:
            # 使用系统默认播放器打开视频
            os.startfile(video_path)
        except Exception as e:
            messagebox.showerror("播放错误", f"无法播放视频: {str(e)}")

    def upload_image_to_get_url(self, image_path):
        # 这里需要实现图片上传逻辑，返回图片URL
        # 为了简化，我们直接返回本地文件路径作为示例
        # 在实际应用中，您需要将图片上传到支持的图床服务并返回URL
        # 例如，可以使用阿里云OSS、腾讯云COS等服务

        # 临时实现：将图片转换为base64格式的data URL
        try:
            with open(image_path, "rb") as img_file:
                import base64
                img_base64 = base64.b64encode(img_file.read()).decode('utf-8')
                # 简单判断图片格式
                if image_path.lower().endswith('.png'):
                    return f"data:image/png;base64,{img_base64}"
                elif image_path.lower().endswith('.jpg') or image_path.lower().endswith('.jpeg'):
                    return f"data:image/jpeg;base64,{img_base64}"
                else:
                    # 默认返回jpeg格式
                    return f"data:image/jpeg;base64,{img_base64}"
        except Exception as e:
            raise Exception(f"图片上传失败: {str(e)}")